import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/home'
import Question from '@/views/question'
import Video from '@/views/video'
import User from '@/views/user'
import Login from '@/views/login'
import Tabbar from '@/components/app-tabbar.vue'
import store from '@/store'
import Article from '@/views/article'
import UserProfile from '@/views/user/profile'
import Chat from '@/views/user/chat/index.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    components: {
      default: Home,
      tabbar: Tabbar
    }
  },
  {
    path: '/question',
    components: {
      default: Question,
      tabbar: Tabbar
    },
    name: 'Question'
  },
  {
    path: '/video',
    components: {
      default: Video,
      tabbar: Tabbar
    },
    name: 'Video'
  },
  {
    path: '/user',
    components: {
      default: User,
      tabbar: Tabbar
    },
    name: 'User'
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '*',
    redirect: '/home'

  },
  {
    path: '/login',
    component: Login,
    name: 'Login'
  },
  {
    path: '/article',
    component: Article,
    name: 'Article'
  },
  {
    path: '/user/profile',
    component: UserProfile
  }
]

const router = new VueRouter({
  routes
})

// 解决vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 前置守卫
// 设置黑名单和白名单
// const blackList = ['Home', 'Question']
// const whiteList = ['Home', 'Question', 'Video', 'Login']
// router.beforeEach((to, from, next) => {
//   const status = whiteList.includes(to.name)
//   if (status || store.state.user.token) {
//     next()
//   } else {
//     next('/login?returnUrl=' + to.fullPath)
//   }
// })

const blackList = ['User']
router.beforeEach((to, from, next) => {
  store.commit('user/clearToken')// 取消请求
  const status = blackList.includes(to.name)
  if (status && !store.state.user.token) next('/login?returnUrl=' + to.fullPath)
  else next()
})

export default router
